package com.zhiwang.planet.mvvm.viewmodel

import android.text.TextUtils
import android.util.Log
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import com.zhiwang.planet.BR
import com.zhiwang.planet.BuildConfig
import com.zhiwang.planet.R
import com.zhiwang.planet.aop.net.LoginRequired
import com.zhiwang.planet.mvvm.model.RestApi
import com.zhiwang.planet.mvvm.model.entity.main.GameTask
import com.zhiwang.planet.mvvm.model.entity.main.TaskReq
import com.zhiwang.planet.sdk.AdListActivity
import com.zhiwang.planet.ui.WebViewActivity
import com.zhiwang.planet.ui.money.CommonListActivity
import com.zhiwang.planet.util.Toaster
import com.zhiwang.planet.util.arrange
import com.zhiwang.planet.util.quickStartActivity
import io.reactivex.functions.Action
import io.reactivex.functions.Consumer
import me.tatarka.bindingcollectionadapter2.ItemBinding
import me.tatarka.bindingcollectionadapter2.OnItemBind
import javax.inject.Inject

data class TaskItem(var name: String,
                    var reward: String,
                    var iconUrl: String,
                    var surplus: String,
                    var tag: String,
                    var link: String,
                    var disable: Boolean = false
) {

    var type = 0

    lateinit var func: (() -> Unit)

    lateinit var linkFunc: ((String) -> Unit)

    constructor() : this("", "", "", "", "", "") {

        type = 1
    }

    fun loadMoreGame() {
        func.invoke()
    }

    val TAG = "TaskItem"

    fun loadLink(v: View) {
        if (disable)
            Toaster.message("招募已满")
        if (TextUtils.isEmpty(link).not())
            linkFunc.invoke(link)
    }

}


class ListMoneyViewModel @Inject constructor(var restApi: RestApi, var activity: AppCompatActivity) : ViewModel() {

    val TAG = "ListMoneyViewModel"

    lateinit var type: String

    val binding = object : OnItemBind<TaskItem> {

        override fun onItemBind(itemBinding: ItemBinding<*>, position: Int, item: TaskItem?) {
            if (position == 0 && item?.type == 1) {
                itemBinding.bindExtra(BR.moneyVm, this@ListMoneyViewModel)
                itemBinding.set(BR.vm, R.layout.item_game_header)
            } else itemBinding.set(BR.vm, R.layout.item_my_task)
        }

    }

    val data = MutableLiveData<List<TaskItem>>()

    val visibility = MutableLiveData<Int>(View.GONE)

    var tasktag: Boolean = false

    var refreshing = MutableLiveData<Boolean>(false)

    fun load() {
        tasktag = true
        restApi.getTaskList(TaskReq(type))
                .arrange(Consumer {

                    val mergeAndMap2Model = mergeAndMap2Model(it.lists, it.prefList ?: listOf())
                    data.value = mergeAndMap2Model
                    visibility.value = if (mergeAndMap2Model.isEmpty()) View.VISIBLE else View.GONE

                    finishRefresh()

                }, Consumer {

                    finishRefresh()
                }, Action {

                })
    }


    fun loadGame() {
        tasktag = false
        restApi.getGameList(TaskReq(type))
                .arrange(Consumer {
                    val mergeAndMap2Model = mergeAndMap2Model(it.lists, it.prefList ?: listOf())

                    val r = arrayListOf<TaskItem>()
                    r.add(TaskItem().apply {
                        func = ::loadPceggGame
                    })
                    r.addAll(mergeAndMap2Model)
                    data.value = r
                    visibility.value = if (mergeAndMap2Model.isEmpty()) View.VISIBLE else View.GONE

                    finishRefresh()

                }, Consumer {
                    finishRefresh()

                }, Action {

                })
    }

    fun loadGaoFan() {
        tasktag = false
        type = "gaofan"
        restApi.getGaoFanGameList(TaskReq(type))
                .arrange(Consumer {
                    val mergeAndMap2Model = mergeAndMap2Model(it.lists, it.prefList ?: listOf())

                    val r = arrayListOf<TaskItem>()
                    r.addAll(mergeAndMap2Model)
                    data.value = r
                    visibility.value = if (mergeAndMap2Model.isEmpty()) View.VISIBLE else View.GONE

                    finishRefresh()

                }, Consumer {
                    finishRefresh()

                }, Action {

                })
    }

    fun loadGaoFanGame() {
//        type = "gaofan"
//        loadGame()
        activity.quickStartActivity(CommonListActivity::class.java)
    }


    fun loadPceggGame() {
        activity.quickStartActivity(AdListActivity::class.java)
    }

    fun loadLink(url: String) {
        WebViewActivity.load(activity, url)
    }


    fun doLoad() {
        if (tasktag)
            load()
        else loadGame()
    }


    private fun finishRefresh() {
        refreshing.value = false
    }

    /**
     *
     * {
    "id": "553",
    "cname": "南瓜小游戏",
    "img": "http://file.ji7.com/images/159341541751488.png",
    "reward_gold": "5000",
    "url": "http://xq.ji7c.com/tasks/553",
    "surplus": "份数补充中",
    "cs": "上新"
    }
     */

    private fun mergeAndMap2Model(lists: List<GameTask>, prefList: List<GameTask>): List<TaskItem> {

        val list1 = map(lists)
        val list2 = map(prefList)
        val r = arrayListOf<TaskItem>()
        r.addAll(list2)
        r.addAll(list1)
        return r
    }


    fun map(prefList: List<GameTask>): List<TaskItem> {

        val sb = StringBuffer()
        return prefList.map {
            sb.delete(0, sb.length)
            sb.append("+")
            sb.append(it.reward)
            TaskItem(it.title,
                    sb.toString(),
                    it.icon,
                    it.surplus ?: "",
                    it.tag,
                    it.link,
                    it.disable()).apply {
                linkFunc = ::loadLink
            }
        }
    }

}